<?

class Vakanz_Relation_Meta extends Vakanz_CRM_Db_Table_Row {
	protected $_prefix = 'relationmeta';

	
	public function save() {
		if ($this->offsetGet(current($this->getTable()->info('primary'))) > 0) {
			$cleanData = $this->_cleanData;
			$newData = $this->_data;
			$changed = $this->isChanged($cleanData, $newData);
			if (!$changed) {
				return $this->offsetGet(current($this->getTable()->info('primary')));
			}
			$data = $this->toArray();
			
			$this->_data = $this->_cleanData;
			$this->{$this->_prefix . '_valid_till'} = date('Y-m-d H:i:s');
			$this->{$this->_prefix . '_status'} = 3;
			parent::save();
			
			unset($data[$this->_prefix.'_id']);
			unset($data[$this->_prefix.'_valid_till']);
			unset($data[$this->_prefix.'_valid_from']);
			unset($data[$this->_prefix.'_status']);
			$object = $this->getTable()->createRow($data);
			$object_autoid = $object->save();
			return $object_autoid;
		} else {
			return parent::save();
		}
	}
	
	protected function isChanged($oldData, $newData) {
		unset($oldData[$this->_prefix . '_valid_till']);
		unset($oldData[$this->_prefix . '_valid_from']);
		unset($oldData[$this->_prefix . '_status']);
		unset($newData[$this->_prefix . '_valid_till']);
		unset($newData[$this->_prefix . '_valid_from']);
		unset($newData[$this->_prefix . '_status']);
		$changedFields = array_diff($oldData, $newData);
		return !empty($changedFields);
	}
	public function delete() {
		$this->relation_valid_till = date('Y-m-d H:i:s');
		$this->relation_status = 5;
		parent::save();
		
	}
}